const Koa = require('koa')
const path = require('path')
const { WebSocketServer } = require('ws')
const { koaBody } = require('koa-body')
const koastatic = require('koa-static')
const wss = new WebSocketServer({ port: 3007 })
const unlinedata = require('./modle/unlinedata')
const userdata = []
wss.on('connection', (ws) => {
    console.log("ws连接成功！")
    ws.on('message', (msg) => {
        if (JSON.parse(msg).userid) {
            const rudata = userdata.find(e => e.id == JSON.parse(msg).userid)
            if (!rudata) {
                userdata.push({
                    id: JSON.parse(msg).userid,
                    ws
                })
            } else {
                rudata.ws = ws
            }
        }
        const enduser = userdata.find(e => e.id == JSON.parse(msg).shou)
        if (enduser) {
            if (enduser.ws.readyState == 3) {
                const { id, ...data } = JSON.parse(msg)
                unlinedata.create({ ids: id, ...data }).then(() => {
                    return
                })
            }
            enduser.ws.send(msg)
        }
        console.log(userdata.length)
        // wss.clients.forEach(e => {
        //     e.send(msg.toString())
        // })
    })
})
const app = new Koa()
const userlogin = require('./router/userlogin')
const hose = require('./router/hose')
const { Json } = require('sequelize/lib/utils')
app.use(koastatic(path.resolve(__dirname, './pubilc/image')))
app.use(koaBody({
    multipart: true,
    formidable: {
        uploadDir: path.join(__dirname, './pubilc/image'),
        keepExtensions: true
    }
}))
app.use(userlogin.routes())
app.use(hose.routes())
app.listen('3006', () => {
    console.log('server is running on port 3006')
})